const vscode = require('vscode');
const path = require('path');
class ColorsViewProvider {

    constructor(context) {
        this._context = context;
    }

    /**
     * @param {vscode.WebviewView} webviewView 
     * @param {vscode.WebviewViewResolveContext} context 
     * @param {vscode.CancellationToken} token 
     */
    resolveWebviewView(webviewView, context, token) {
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [vscode.Uri.file(path.join(this._context.extensionPath, 'src/webview/colors'))],
        };
        // 设置 Webview 的 HTML 内容
        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        // 处理 Webview 的消息
        webviewView.webview.onDidReceiveMessage(this.quickColor);
    }

    /**
     * 
     * @param {{hex:string,number:number}} color 
     */
    quickColor(color) {
        if (vscode.window.activeTextEditor) {
            const { selection, document } = vscode.window.activeTextEditor;
            let selectedTxt = document.getText(new vscode.Range(selection.start, selection.end))
            if (selectedTxt.match(/\d+/g)) {
                selectedTxt = selectedTxt.replace(/\d+/g, color.number);
            } else {
                selectedTxt = color.number;
            }
            const edit = new vscode.WorkspaceEdit();
            edit.replace(document.uri, selection, selectedTxt);
            vscode.workspace.applyEdit(edit);
        }
    }

    /**
     * @param {vscode.Webview} webview 
     * @returns {string}
     */
    _getHtmlForWebview(webview) {
        const scriptColorsPath = vscode.Uri.file(path.join(this._context.extensionPath, 'src/webview/colors', 'colors.js'));
        const scriptColorsUri = webview.asWebviewUri(scriptColorsPath);
        const scriptRenderPath = vscode.Uri.file(path.join(this._context.extensionPath, 'src/webview/colors', 'render.js'));
        const scriptRenderUri = webview.asWebviewUri(scriptRenderPath);

        const styleCSSPath = vscode.Uri.file(path.join(this._context.extensionPath, 'src/webview/colors', 'style.css'));
        const styleCSStUri = webview.asWebviewUri(styleCSSPath);
        return `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link href="${styleCSStUri}" rel="stylesheet">
                <script src="${scriptColorsUri}"></script>
                <title>Colors View</title>
            </head>
            <body>
                 <script src="${scriptRenderUri}"></script>
            </body>
            </html>`;
    }


    /**
     * 
     * @param {vscode.ExtensionContext} context 
     */
    static init(context) {
        context.subscriptions.push(vscode.window.registerWebviewViewProvider('mir_script_activity_color', new ColorsViewProvider(context)));
    }
}

module.exports = { ColorsViewProvider }